package com.superai.controller;

import io.github.imfangs.dify.client.DifyChatflowClient;
import io.github.imfangs.dify.client.callback.ChatStreamCallback;
import io.github.imfangs.dify.client.enums.ResponseMode;
import io.github.imfangs.dify.client.event.ErrorEvent;
import io.github.imfangs.dify.client.event.MessageEndEvent;
import io.github.imfangs.dify.client.event.MessageEvent;
import io.github.imfangs.dify.client.model.chat.*;
import io.github.imfangs.dify.client.model.common.SimpleResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工作流编排对话控制器
 * 用于处理工作流编排对话型应用的API请求
 */
@RestController
@RequestMapping("/chatflow")
@RequiredArgsConstructor
@Slf4j
public class ChatflowController {

    private final DifyChatflowClient chatflowClient;
    private final ConcurrentHashMap<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    /**
     * 发送工作流编排对话消息（阻塞模式）
     *
     * @param message 聊天消息请求
     * @return 聊天消息响应
     */
    @PostMapping("/messages")
    public ResponseEntity<ChatMessageResponse> sendChatflowMessage(@RequestBody ChatMessage message) {
        try {
            // 确保使用阻塞模式
            message.setResponseMode(ResponseMode.BLOCKING);
            ChatMessageResponse response = chatflowClient.sendChatMessage(message);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("发送工作流编排对话消息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 发送工作流编排对话消息（流式模式）
     *
     * @param message 聊天消息请求
     * @return SSE发射器
     */
    @PostMapping(value = "/messages/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sendChatflowMessageStream(@RequestBody ChatMessage message) {
        // 创建SSE发射器
        SseEmitter emitter = new SseEmitter(0L);
        String emitterId = message.getUser() + "_" + System.currentTimeMillis();
        emitters.put(emitterId, emitter);

        // 设置为流式模式
        message.setResponseMode(ResponseMode.STREAMING);

        // 处理SSE发射器关闭事件
        emitter.onCompletion(() -> emitters.remove(emitterId));
        emitter.onTimeout(() -> emitters.remove(emitterId));
        emitter.onError(e -> emitters.remove(emitterId));

        try {
            // 发送流式消息
            chatflowClient.sendChatMessageStream(message, new ChatStreamCallback() {
                @Override
                public void onMessage(MessageEvent event) {
                    try {
                        emitter.send(SseEmitter.event()
                                .name("message")
                                .data(event));
                    } catch (IOException e) {
                        log.error("发送SSE消息事件失败", e);
                        emitter.completeWithError(e);
                    }
                }

                @Override
                public void onMessageEnd(MessageEndEvent event) {
                    try {
                        emitter.send(SseEmitter.event()
                                .name("message_end")
                                .data(event));
                        emitter.complete();
                    } catch (IOException e) {
                        log.error("发送SSE消息结束事件失败", e);
                        emitter.completeWithError(e);
                    }
                }

                @Override
                public void onError(ErrorEvent event) {
                    try {
                        emitter.send(SseEmitter.event()
                                .name("error")
                                .data(event));
                        emitter.complete();
                    } catch (IOException e) {
                        log.error("发送SSE错误事件失败", e);
                        emitter.completeWithError(e);
                    }
                }

                @Override
                public void onException(Throwable throwable) {
                    log.error("流式消息异常", throwable);
                    emitter.completeWithError(throwable);
                }
            });
        } catch (Exception e) {
            log.error("发送工作流编排对话流式消息失败", e);
            emitter.completeWithError(e);
        }

        return emitter;
    }

    /**
     * 获取会话列表
     *
     * @param user 用户ID
     * @param lastId 上一页最后一条记录的ID（可选）
     * @param limit 每页记录数（可选）
     * @param order 排序方式（可选）
     * @return 会话列表响应
     */
    @GetMapping("/conversations")
    public ResponseEntity<ConversationListResponse> getConversations(
            @RequestParam String user,
            @RequestParam(required = false) String lastId,
            @RequestParam(defaultValue = "20") Integer limit,
            @RequestParam(defaultValue = "-updated_at") String order) {
        try {
            ConversationListResponse response = chatflowClient.getConversations(user, lastId, limit, order);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("获取工作流编排对话会话列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 重命名会话
     *
     * @param conversationId 会话ID
     * @param request 重命名请求
     * @return 更新后的会话信息
     */
    @PutMapping("/conversations/{conversationId}/rename")
    public ResponseEntity<Conversation> renameConversation(
            @PathVariable String conversationId,
            @RequestBody ChatController.RenameConversationRequest request) {
        try {
            Conversation response = chatflowClient.renameConversation(
                    conversationId,
                    request.getName(),
                    request.isAutoName(),
                    request.getUser());
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("重命名工作流编排对话会话失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除会话
     *
     * @param conversationId 会话ID
     * @param user 用户ID
     * @return 简单响应
     */
    @DeleteMapping("/conversations/{conversationId}")
    public ResponseEntity<SimpleResponse> deleteConversation(
            @PathVariable String conversationId,
            @RequestParam String user) {
        try {
            SimpleResponse response = chatflowClient.deleteConversation(conversationId, user);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("删除工作流编排对话会话失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取会话历史消息
     *
     * @param conversationId 会话ID
     * @param user 用户ID
     * @param firstId 第一页第一条记录的ID（可选）
     * @param limit 每页记录数（可选）
     * @return 消息列表响应
     */
    @GetMapping("/conversations/{conversationId}/messages")
    public ResponseEntity<MessageListResponse> getMessages(
            @PathVariable String conversationId,
            @RequestParam String user,
            @RequestParam(required = false) String firstId,
            @RequestParam(defaultValue = "20") Integer limit) {
        try {
            MessageListResponse response = chatflowClient.getMessages(conversationId, user, firstId, limit);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("获取工作流编排对话会话历史消息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 消息反馈
     *
     * @param messageId 消息ID
     * @param rating 评分（like/dislike）
     * @param user 用户ID
     * @param text 反馈文本（可选）
     * @return 简单响应
     */
    @PostMapping("/messages/{messageId}/feedbacks")
    public ResponseEntity<SimpleResponse> feedbackMessage(
            @PathVariable String messageId,
            @RequestParam String rating,
            @RequestParam String user,
            @RequestParam(required = false) String text) {
        try {
            SimpleResponse response = chatflowClient.feedbackMessage(messageId, rating, user, text);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("工作流编排对话消息反馈失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取建议问题
     *
     * @param messageId 消息ID
     * @param user 用户ID
     * @return 建议问题响应
     */
    @GetMapping("/messages/{messageId}/suggested-questions")
    public ResponseEntity<SuggestedQuestionsResponse> getSuggestedQuestions(
            @PathVariable String messageId,
            @RequestParam String user) {
        try {
            SuggestedQuestionsResponse response = chatflowClient.getSuggestedQuestions(messageId, user);
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("获取工作流编排对话建议问题失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
